package com.zhugang.week02;

/**
 * @program algorithms
 * @description: reverseList
 * @author: chanzhugang
 * @create: 2022/05/30 16:30
 */
public class ReverseList {

    /**
     * 206. 反转链表
     *
     * @param head
     * @return
     */
    public ListNode reverseList(ListNode head) {
        // 开辟新链表，每次遍历p.next = newNode; newNode = p (反转一次)
        ListNode newHead = null;
        ListNode p = head;
        while (p != null) {
            ListNode temp = p.next;
            p.next = newHead;
            newHead = p;
            p = temp;
        }
        return newHead;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}